"""
API配置管理
集中管理所有配置，避免硬编码
"""
import os
from typing import Optional
from pydantic_settings import BaseSettings
from pydantic import Field
from functools import lru_cache


class Settings(BaseSettings):
    """应用配置"""
    
    # PostgreSQL配置
    postgres_user: str = Field("admin", env="POSTGRES_USER")
    postgres_password: str = Field("newhand", env="POSTGRES_PASSWORD")
    postgres_db: str = Field("aipaper_db", env="POSTGRES_DB")
    postgres_host: str = Field("localhost", env="POSTGRES_HOST")
    postgres_port: int = Field(15432, env="POSTGRES_PORT")  # 注意端口是15432
    
    # MongoDB配置（用于爬虫数据存储）
    mongodb_user: str = Field("admin", env="MONGODB_USER")
    mongodb_password: str = Field("newhand", env="MONGODB_PASSWORD")
    mongodb_host: str = Field("localhost", env="MONGODB_HOST")
    mongodb_port: int = Field(27017, env="MONGODB_PORT")
    mongodb_db: str = Field("crawler_db", env="MONGODB_DB")
    
    # Redis配置
    redis_host: str = Field("localhost", env="REDIS_HOST")
    redis_port: int = Field(6379, env="REDIS_PORT")
    redis_password: Optional[str] = Field(None, env="REDIS_PASSWORD")
    redis_db: int = Field(0, env="REDIS_DB")
    redis_rate_limit_db: int = Field(1, env="REDIS_RATE_LIMIT_DB")
    
    # JWT配置
    jwt_secret: str = Field(
        "aipaper-jwt-secret-key-2025",
        env="JWT_SECRET",
        description="JWT密钥"
    )
    jwt_algorithm: str = Field("HS256", env="JWT_ALGORITHM")
    jwt_expiration_hours: int = Field(24, env="JWT_EXPIRATION_HOURS")
    
    # API配置
    api_keys: str = Field("", env="API_KEYS")  # 简化为字符串
    require_auth: bool = Field(False, env="REQUIRE_AUTH")  # 默认关闭认证以便测试
    cors_origins: str = Field("*", env="CORS_ORIGINS")  # 简化为字符串
    rate_limit_per_minute: int = Field(60, env="RATE_LIMIT_PER_MINUTE")
    
    # 应用配置
    api_port: int = Field(8001, env="API_PORT")
    log_level: str = Field("INFO", env="LOG_LEVEL")
    debug: bool = Field(False, env="DEBUG")
    
    # 路径配置
    task_queue_path: Optional[str] = Field(None, env="TASK_QUEUE_PATH")
    crawler_service_path: Optional[str] = Field(None, env="CRAWLER_SERVICE_PATH")
    
    @property
    def postgres_url(self) -> str:
        """构建PostgreSQL连接URL"""
        return f"postgresql://{self.postgres_user}:{self.postgres_password}@{self.postgres_host}:{self.postgres_port}/{self.postgres_db}"
    
    @property
    def mongodb_uri(self) -> str:
        """构建MongoDB连接URI"""
        return f"mongodb://{self.mongodb_user}:{self.mongodb_password}@{self.mongodb_host}:{self.mongodb_port}/"
    
    def get_api_keys_dict(self) -> dict:
        """将API密钥字符串解析为字典"""
        if not self.api_keys:
            return {}
        
        keys = {}
        for entry in self.api_keys.split(","):
            if ":" in entry:
                key, name = entry.split(":", 1)
                keys[key.strip()] = name.strip()
        return keys
    
    def get_cors_origins_list(self) -> list:
        """将CORS来源字符串解析为列表"""
        if not self.cors_origins or self.cors_origins == "*":
            return ["*"]
        return [origin.strip() for origin in self.cors_origins.split(",")]
    
    model_config = {
        "env_file": ".env",
        "env_file_encoding": "utf-8",
        "case_sensitive": False,
        "extra": "ignore"  # 忽略额外的环境变量
    }


@lru_cache()
def get_settings() -> Settings:
    """获取配置单例"""
    return Settings()


# 配置实例
settings = get_settings()